<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建学习主题' : "编辑学习主题" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入文件名称"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="subjectDesp">
          <el-input autosize type="textarea" v-model="ruleForm.subjectDesp" placeholder="请输入简介"></el-input>
        </el-form-item>

        <el-form-item label="学习重点" prop="subjectimportant">
          <el-input v-model="ruleForm.subjectimportant" placeholder="请输入学习重点"></el-input>
        </el-form-item>

        <el-form-item label="学习形式" prop="studyWay">
          <el-select v-model="ruleForm.studyWay" placeholder="请选择学习形式">
            <el-option label="集体学习讨论" value="集体学习讨论" />
            <el-option label="专题辅导报告" value="专题辅导报告" />
            <el-option label="现场调研" value="现场调研" />
          </el-select>
        </el-form-item>

        <el-form-item label="学习计划日期" prop="planDate">
          <el-date-picker
            v-model="ruleForm.planDate"
            type="daterange"
            range-separator="To"
            start-placeholder="请选择学习计划开始日期"
            end-placeholder="请选择学习计划结束日期"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
            @change="changePlanDate"

          />
        </el-form-item>

        <el-form-item label="学习范围" prop="studyRange">
          <el-input v-model="ruleForm.studyRange" placeholder="请输入学习范围"></el-input>
        </el-form-item>

        <el-form-item label="发布日期" prop="pubDate">
          <el-date-picker
            v-model="ruleForm.pubDate"
            type="date"
            placeholder="请选择发布日期"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="工作要求" prop="subjectRequirement">
          <el-input autosize type="textarea" v-model="ruleForm.subjectRequirement" placeholder="请输入工作要求"></el-input>
        </el-form-item>

        <el-form-item label="学习内容" prop="studyContent">
          <t-editor v-model="ruleForm.studyContent" @input="inputContent" style="width: 100%;"/>
        </el-form-item>

        <el-form-item label="附件" prop="studyFileNames">
          <upload-file-result :fileList="fileList" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传附件
          </el-button>
          <span style="margin-left: 10px;">请上传不超过20M的文件，格式：jpg/jpeg/png/mp4/doc/docx/xls/xlsx/ppt/pptx/pdf</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "backendLearnSubjectAdd" }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import tEditor from "@/components/tinymceEditor/tEditor.vue"
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { format } from '@/plugins/moment.js'
import { uploadFile } from '@/utils/file.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { useAuthStore } from '@/stores/modules/auth.js';
import uploadFileResult from "@/components/backend/fileList.vue"

/* 路由 */
const route = useRouter()

/* 用户信息 */
const authStore = useAuthStore()

onMounted(() => {
  if(route.currentRoute.value.query.id){
    getSubjectDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getSubjectDetail = () => {
  loading.value = true
  http.$GET("/TheoryStudyM/GetTheoryStudySubjectLocalDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })
    
    /* 处理学习开始和结束日期 */
    ruleForm.value.studyStartDate = format(res.result.studyStartDate)
    ruleForm.value.studyEndDate = format(res.result.studyEndDate)
    /* 处理学习计划日期 */
    ruleForm.value.planDate = [ruleForm.value.studyStartDate, ruleForm.value.studyEndDate]

    /* 处理发布日期 */
    ruleForm.value.pubDate = format(res.result.pubDate)

    /* 附件 */
    if(!isJsonString(res.result.studyFileNames)){
      fileList.value = []
      ruleForm.value.studyFileNames = ""
      return
    }
    if(res.result.studyFileNames != ''){
      let fileName = JSON.parse(res.result.studyFileNames)

      if(fileName.filePathArray){
        fileList.value = fileName.filePathArray
      }else{
        fileList.value = []
        ruleForm.value.studyFileNames = ""
      }
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 日期禁选范围 */
const disabledDate = (time) => {
  return time.getTime() < new Date() - 24 * 60 * 60 * 1000
}

/* 日期选择 */
const changePlanDate = (val) => {
  if(val.length){
    ruleForm.value.studyStartDate = val[0]
    ruleForm.value.studyEndDate = val[1]
  }
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单值 */
const ruleForm = ref({
  id: "",
  name: "",
  subjectDesp: "",
  subjectimportant: "",
  studyWay: "",
  studyStartDate: "",
  studyEndDate: "",
  pubDate: "",
  studyRange: "",
  subjectRequirement: "",
  studyContent: "",
  studyFileNames: "",
})

/* 附件列表 */
const fileList = ref([])
/* 是否有上传附件 */
const isUploadFile = ref(false)

/* 校验附件规则 */
const checkFile = (rule, value, callback) => {
  if (!ruleForm.value.studyFileNames) {
    callback(new Error('请上传附件'))
  } else {
    callback()
  }
} 

/* 表单校验规则 */
const rules = reactive({
  name: [
    { required: true, message: '请输入文件名称', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  subjectDesp: [
    { required: true, message: '请输入简介', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  subjectimportant: [
    { required: true, message: '请输入学习重点', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  studyContent: [
    { required: true, message: '请输入学习内容', trigger: 'blur' }
  ],
  studyWay: [
    { required: true, message: '请选择学习形式', trigger: 'change' }
  ],
  pubDate: [
    { required: true, message: '请选择发布日期', trigger: 'change' }
  ],
  planDate: [
    { required: true, message: '请选择学习计划日期', trigger: 'change' }
  ],
  studyRange: [
    { required: true, message: '请输入学习范围', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  subjectRequirement: [
    { required: true, message: '请输入工作要求', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  /* studyFileNames: [
    { required: true, validator: checkFile, message: '请上传附件', trigger: 'change' }
  ], */
})

/* 富文本内容修改 */
const inputContent = (newVal) => {
  if(newVal){
    ruleFormRef.value.clearValidate('studyContent')
  }
  ruleForm.value.studyContent = newVal
}

/* 点击上传文件 */
const uploadEvent = () => {
  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG,.mp4,.MP4,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF"

  uploadFile({ accept: fileType, multiple: true }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG|mp4|MP4|doc|docx|xls|png|xlsx|ppt|pptx|pdf|DOC|DOCX|XLS|XLSX|PPT|PPTX|PDF)$/)){
      ruleForm.value.studyFileNames = ""
      fileList.value = []
      isUploadFile.value = false
      return 
    }

    /* 文件大小判断 */
    if(!testFileSize(res, 20*1024*1024)){
      ruleForm.value.studyFileNames = ""
      fileList.value = []
      isUploadFile.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res) {
      isUploadFile.value = true
      ruleForm.value.studyFileNames = res
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate("studyFileNames")
      /* 文件列表 */
      fileList.value = res
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交新增、编辑 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新附件时不传值 */
      if(!isUploadFile.value) {
        delete ruleForm.value.studyFileNames
      }

      /* 参数处理 */
      const formData = new FormData();
      
      for(let k in ruleForm.value){
        if(isUploadFile.value){
          if(k == 'studyFileNames'){
            for(let j in ruleForm.value[k]){
              if(j < ruleForm.value[k].length){
                formData.append(k, ruleForm.value[k][j]);
              }
            }
          }else{
            formData.append(k, ruleForm.value[k]);
          }
        }else{
          formData.append(k, ruleForm.value[k]);
        }
      }

      if(authStore.auth_token){
        formData.append('authToken', authStore.auth_token)
      }

      http.$POST("/TheoryStudyM/AddOrUpdateTheoryStudySubjectLocal", formData).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage({
            type: 'warning',
            message: '操作失败',
          })
        }else{
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          route.push({
            path: "/backend/learn-subject"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage({
          type: 'warning',
          message: '操作失败',
        })
      })
    }else{
      ElMessage({
        type: 'warning',
        message: '请先完成必填项',
      })
    }
  })
}

/* 重置表单项 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  fileList.value = []
  isUploadFile.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/learn-subject",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>